response.title="Classic Short Story"
import logging
log=logging.getLogger("CopyPaste")


if not session.categories:
#    session.categories=db.select(db.category.name)
    session.categories=[r.name for r in db().select(db.category.ALL)]


response.menu = [['Russian', True, URL(r=request,f='index',args=['lovestory'])],
['American', True, URL(r=request,f='index',args=['programming'])],['English', True, URL(r=request,f='index',args=['technology'])],
['Vietnam', True, URL(r=request,f='index',args=['science'])]]


def register():
    form=SQLFORM(db.person,fields=['alias', 'email','password'])
    if form.accepts(request.vars,session):
          session.authorized=form.vars.id
          session.email=form.vars.email
          session.alias=form.vars.alias
          logging.info("lalalal")
          session.flash='user registered'
          redirect(URL(r=request,f='index'))
    return dict(form=form)


	
def login():
    db.person.email.requires=IS_NOT_EMPTY()    
    form=SQLFORM(db.person,fields=['email','password'])
    if FORM.accepts(form,request.vars,session):
       users=db(db.person.email==form.vars.email)\
               (db.person.password==form.vars.password).select()
       if len(users):
          session.authorized=users[0].id
          session.email=users[0].email
          session.alias=users[0].alias
          session.flash='user logged in'
          redirect(URL(r=request,f='index'))
       else:
          form.errors['password']='invdalid password'
    return dict(form=form)

def logout():
	logging.debug('TEST INSIDE WEB@PY')
	logging.info("LOGOUT ")
	session.authorized=None
	session.email=None
	session.alias=None
	session.flash='user logged out'
	redirect(URL(r=request,f='index'))

def index():
	sorts={'new':~db.news.post_time,
			'hot':~db.news.hotness,
			'score':~db.news.score}
	try:
		page=int(request.args[2])
		log.warning('page value is got is %s',page)
	except:
		page=0
		log.warning('PAGE IS 0')
	try:
		log.warning(' hot value is')
		sort=request.args[1]
		log.warning(' hot value is%',sort)
	except:
		log.warning(' hot value is default')
		sort='hot'
		log.warning(' confirm hot value is default')
	log.warning('hot value is %s',sort)
	orderby=sorts[sort]
	log.warning('orderby is %s',orderby)
	try:
		log.warning('category value is')
		category=request.args[0]
		log.info('category is %s',category)
	except:
		log.warning('category value is default')
		category='science'
		log.info('default category is %s',category)
	limitby=(9*page,9*(page+1)+1)
	log.info('after limit by caculation limit is %s',limitby)
	news=db(db.news.category==category).select(orderby=orderby,limitby=limitby)
	log.info('after news query')
	return dict(sorttest=sorts,category=category,news=news,sort=sort,sorts=sorts.keys(),page=page)



def bookmark():
    try: item=db(db.news.id==request.args[0]).select()[0]
    except: redirect(URL(r=request,f='index'))
    item.update_record(clicks=item.clicks+1)
    redirect(item.url)


def read():
	log.info("******************************************")
	post_id = int(request.args[0])
	post = db(db.news.id == post_id).select()[0]
	post.update_record(clicks=post.clicks+1)
	form = FORM(
		INPUT(_class='hover-star',_type='radio',_name='rating',_value=1,_title='Very poor'),
		INPUT(_class='hover-star',_type='radio',_name='rating',_value=2,_title=' poor'),
		INPUT(_class='hover-star',_type='radio',_name='rating',_value=3,_title='normal'),
		INPUT(_class='hover-star',_type='radio',_name='rating',_value=4,_title='good'),
		INPUT(_class='hover-star',_type='radio',_name='rating',_value=5,_title='Very good'),
		SPAN(_id='hover-test', _style="margin:0 0 0 20px;"),
		DIV(""),
		INPUT(_type='submit', _value="save"),_action=URL(r=request,f='rating',args=[request.args[0]]))
	log.info('test inside web2py %s',request.args[0])
	log.info('***********************************************************************')
	if form.accepts(request.vars, session):
		response.flash = 'Thanks for rating'
	elif form.errors:
		response.flash = 'form is invalid'
	return dict(post = post,form=form)


	
	
	
# Star rating for Story
def rating():
	log.info('RATING FUNCTION')
	log.debug(' request.vars.rating is %s',request.vars.rating)
	log.warning('log warning')
	news=db(db.news.id==request.args[0]).select()[0]
	log.warning(' news[0] is %s', news)
	news.update_record(score= int(request.vars.rating) + news.score, scoringtime=news.scoringtime+1)
	redirect(URL(r=request,f='read',args=[request.args[0]]))
	return dict()
	
def post(): 
	if not session.authorized:
		redirect(URL(r=request,f='login'))
	form=FORM(TABLE(
	TR('TITLE', INPUT(_name="title",_type="text")),
	TR('Category',INPUT(_name="category",_type="text",_value="programming")),
	TR('Writer',INPUT(_name="writer",_type="text")),
	TR('publish_year',INPUT(_name="publish",_type="text")),
	TR('URL',INPUT(_name="url",_type="text")),
	TR('Foreword',INPUT(_name="foreword",_type="text"))),
	TABLE(
	TR(DIV(TEXTAREA(_name="msgpost",_id="msgpost", _cols="50", _rows="10"))),
	TR(INPUT(_type="submit",_value="Save"))))
	db.news.insert(title=request.vars.title,
					category=request.vars.category,
					writer =request.vars.writer,
					publish= request.vars.publish,
					foreword=request.vars.foreword,
					url=request.vars.url,
					story=request.vars.msgpost,
					author=session.authorized,
					author_alias=session.alias,
					)
	if form.accepts(request.vars,session):
		session.flash='news posted'
		redirect(URL(r=request,f='index',args=[form.vars.category]))
	return dict(form=form)
def edit_post():
	if not session.authorized:
		redirect(request.env.http_referer)
	id=request.args[0]
	log.info('id before try is %s',id)
	try:
		news=db(db.news.id==id).select()[0]
		log.info('news id is %s',news)
	except:
		redirect(URL(r=request,f='index'))
		log.info('redirect to index')
	form=FORM(TABLE(
	TR('TITLE', INPUT(_name="title",_type="text",_value=news.title)),
	TR('Category',INPUT(_name="category",_type="text",_value=news.category)),
	TR('URL',INPUT(_name="url",_type="text",_value=news.url)),
	TR('Foreword',INPUT(_name="foreword",_type="text",_value=news.foreword)),
	TR('Writer',INPUT(_name="writer",_type="text",_value=news.writer)),
	TR('Publish',INPUT(_name="publish",_type="text",_value=news.publish))),
	TABLE(
	TR(DIV(TEXTAREA(_name="msgpost",_id="msgpost", _cols="50", _rows="10",_value=XML(news.story)))),
	TR(INPUT(_type="submit",_value="Save"))))
	news.update_record(
					title=request.vars.title,
					category=request.vars.category,
					foreword=request.vars.foreword,
					writer=request.vars.writer,
					publish=request.vars.publish,
					url=request.vars.url,
					story=request.vars.msgpost,
					author=session.authorized,
					author_alias=session.alias,
					)
	log.info('id after try is %s',id)
	if form.accepts(request.vars,session):
		session.flash='comment edited'
		redirect(URL(r=request,f='index'))
	return dict(form=form)


def report():
	try:
		db(db.news.id==request.args[0]).update(flagged=True)
		session.flash='thanks for your feedback'
	except:
		session.flash='internal error'
	redirect(request.env.http_referer)

def delete():
    if not session.authorized: redirect(request.env.http_referer)
    try:
        news=db(db.news.id==request.args[0]).select()[0]
        if news.author==session.authorized:
            db(db.news.id==request.args[0]).delete()
        session.flash='news item deleted'
    except:
        session.flash='internal error'
    redirect(URL(r=request,f='index',args=[news.category]))

def vote():
    if not session.authorized: redirect(request.env.http_referer)
    news=db(db.news.id==request.args[1]).select()[0]
    if request.args[0]=='up':
       news.update_record(score=news.score+1)
    elif request.args[0]=='down':
       news.update_record(score=news.score-1)
    redirect(request.env.http_referer)

def permalink():
    try: comment=db(db.comment.id==request.args[0]).select()[0]
    except: redirect(request.env.http_referer)
    comments=db(db.comment.news==comment.news).select(orderby=db.comment.score)
    news=comment.news
    items=[]
    tree={}
    forms={}
    pivot=None
    for c in comments:
        if not tree.has_key(c.parente): tree[c.parente]=[c]
        else: tree[c.parente].append(c)
        if c.id==comment.id: pivot=c.parente
        if session.authorized:
           f=SQLFORM(db.comment,fields=['body'],labels={'body':''})
           f.vars.author=session.authorized          
           f.vars.author_alias=session.alias
           f.vars.news=news
           f.vars.parente=c.id
           if f.accepts(request.vars,formname=str(c.id)):
              session.flash='comment posted'
              redirect(URL(r=request,args=request.args))
           forms[c.id]=f
    tree[pivot]=[comment]
    response.view='default/comments.html'
    return dict(item=None,form=None,tree=tree,forms=forms,parent=pivot)

def vote_comment():
    if not session.authorized: redirect(request.env.http_referer)
    comment=db(db.comment.id==request.args[1]).select()[0]
    if request.args[0]=='up':
       comment.update_record(score=comment.score+1)
    elif request.args[0]=='down':
       comment.update_record(score=comment.score-1)
    redirect(request.env.http_referer)

def report_comment():
    try:
        db(db.comment.id==request.args[0]).update(flagged=True)
        session.flash='thanks for your feedback'
    except:
        session.flash='internal error'
    redirect(request.env.http_referer)

def person():
	session.flash='sorry, not yet implemented'
	redirect(request.env.http_referer)


def comments():
	try: news=int(request.args[0])
	except: redirect(URL(r=request,f='index'))
	if session.authorized:
		form=SQLFORM(db.comment,fields=['body'],labels={'body':''})
		form.vars.author=session.authorized
		form.vars.author_alias=session.alias
		form.vars.news=news
		if form.accepts(request.vars,formname='0'): 
			item=db(db.news.id==news).select()[0]
			item.update_record(comments=item.comments + 1)
			response.flash='comment posted'
			
	else: form=None
	try:
		item=db(db.news.id==news).select()[0]
		comments=db(db.comment.news==news).select(orderby=~db.comment.score)
	except: redirect(URL(r=request,f='index'))
	tree={}
	forms={}
	for c in comments:
		if not tree.has_key(c.parente): tree[c.parente]=[c]
		else: tree[c.parente].append(c)
		if session.authorized:
			f=SQLFORM(db.comment,fields=['body'],labels={'body':''})
			f.vars.author=session.authorized          
			f.vars.author_alias=session.alias
			f.vars.news=news
			f.vars.parente=c.id
			if f.accepts(request.vars,formname=str(c.id)):
				session.flash='comment posted'
				redirect(URL(r=request,args=request.args))
			forms[c.id]=f
	log.info('tree is %s',tree)
	return dict(item=item,form=form,tree=tree,forms=forms,parent=0,news=news)

def edit_comment():
    if not session.authorized: redirect(request.env.http_referer)
    id=request.args[0]
    try:
        comment=db(db.comment.id==id).select()[0]
        if not comment.author==session.authorized: raise Exception
    except: redirect(URL(r=request,f='index'))
    form=SQLFORM(db.comment,comment,fields=['body'],showid=False,deletable=True,labels={'body':'Comment'})
    if form.accepts(request.vars,session):
        session.flash='comment edited'
        redirect(URL(r=request,f='comments',args=[comment.news]))
    return dict(form=form)

### todo:
"""
prevent users from voting twice: vote, vote_comment
adjust layout
allow different types of news sorting
"""
